package com.redhat.auth.exception;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ErrorResourceService{
	
	private static Logger logger = LoggerFactory.getLogger(ErrorResourceService.class);
	
	/**
	 * 
	 * @param code
	 * @param defaultMessage
	 * @return
	 */
	public static String getMessage(String key,HttpServletRequest request){
	    String message;
		String path = "exception/"+getLocale(request)+"/exception";
		String keyValue = null;
		ResourceBundle resource = null;
		//读取resources
		try {
		   resource = ResourceBundle.getBundle(path);
		   message = resource.getString(key);
		}catch(MissingResourceException e){
			message = defaultConv(key);
			//不提示英文，只提示中文
			if(!getLocale(request).equals("en"))
		    logger.info("exeception I18n warn,can not find exception Code:"+key+"-->"+keyValue);
		}catch (Exception e) {// add by :vakin jiang
            return key;
        }
		return message;
	}
	
	
	private static String getLocale(HttpServletRequest request){
		//从session中取国际化值
		String language  = (String)request.getSession().getAttribute("IL18N-LANGUAGE");
		//从cookies中取国际化值
		if(language==null || "".equals(language)) language = getCookieLanguage(request);
		//session或cookies中都未有，则读取客户端浏览器的设置
		if(language==null || "".equals(language)) language = request.getLocale().getLanguage();
		return language;
	}
	
	/**
	 * 获取cookie中的国际化语言设置
	 * @param request
	 * @return
	 */
	private static String getCookieLanguage(HttpServletRequest request){
		Cookie[] cookies= request.getCookies();
		if(cookies==null)return null;
		for(int i=0;i<cookies.length;i++){
			Cookie cookie =  cookies[i];
			if(cookie.getName().equals("IL18N-LANGUAGE")){
				return cookie.getValue();
			}
		}
		return null;
	}
	
	/**
	 * 自动转换，将英文key中的下划线及中划线转换为空格
	 * @param key
	 * @return
	 */
	private static String defaultConv(String key){
		key = key.replace("_", " ");
		key = key.replace("-", " ");
		return key;
	}
}
